<?php
namespace app\pay\controller\yop;

use think\Controller;
use pay\yop\Config;

use pay\yop\lib\Util\YopSignUtils;
use phpmailer\Email;
use customtool\Utils;

class CallbackDaifu extends Controller {
    private $cfg = null;
    
    public function _initialize() {
        $this->cfg = new Config();
    }
    
    //结果通知返回原文数据
    public function index() {
        $source = $_REQUEST["response"]; 
        //返回的密文
        //还原出原文
        $data = YopSignUtils::decrypt($source, $this->cfg->C('private_key'), $this->cfg->C('yop_public_key'));
        Email::send('wowchky@163.com', '易宝代付通知数据', $data);
        // return 'SUCCESS';
        $dataArr = json_decode($data, true);
        $resPayDaifuApply = model('PayDaifuApply')->get(['mchnt_orderid' => $dataArr['orderId']]);
        $resPayBis        = model('PayBis')->get(['merchant_id' => $resPayDaifuApply->merchant_id]);
        $resPayPlatform   = model('PayPlatform')->get(['id' => $resPayBis->platform_id]);
        $statusCode = $dataArr['transferStatusCode']; // 打款状态(0025已接收 0026已汇出 0027已退款 0028已拒绝 0029待复核 0030未知)
        $bankStatus = $dataArr['bankTrxStatusCode'];  // 银行处理状态 S已成功  I银行处理中  F出款失败  W未出款  U未知
        
        if($statusCode == '0026') {
            if($bankStatus == 'S') {
                $resUpdate = payBisRemitSuccess($resPayBis, $resPayPlatform, $resPayDaifuApply); // 更新商户金额数据等  
            } else {
                $resUpdate = payBisRemitIFWU($resPayDaifuApply, $bankStatus, $dataArr['bankMsg']);
            }
        }

        if($statusCode == '0027') {
            $resUpdate = payBisRefund($resPayBis, $resPayPlatform, $resPayDaifuApply); // 更新商户金 额数据等 
        }

        if($resUpdate) {
            /*
            * 通过消息队列的形式给请求方推送异步通知 
            *
            * 推送异步通知给客户端提供的回调地址
            */           
            // 异步返回给客户端的数据组装
            $result = $this->responseData($resPayDaifuApply, $data, $resPayBis->md5key);

            // 消息队列
            \think\Queue::push('app\queue\controller\Daifu@fire', $result, $queue = 'payCallbackDaifuQueue');
            return 'SUCCESS';
        }
    }
    
    /*
     *  异步返回给客户端的数据组装
     */
    private function responseData($resPayDaifuApply, $data, $md5key) {
        $retData = json_decode($data, true);
        $result = array(
            'msg'           => $retData['bankMsg'],
            'merchant_id'   => $resPayDaifuApply->merchant_id,  // 商户号        
            'mchnt_batchid' => $retData['batchNo'],              // 出款批次号
            'mchnt_orderid' => $retData['orderId'],              // 出款订单号
            'amount'        => $resPayDaifuApply->amount,        // 出款金额 
            'status'        => $resPayDaifuApply->status,        // 打款状态
            'bank_status'   => $resPayDaifuApply->bank_status,   // 银行处理状态
        );
        return callbackDaifuTrue($result, $md5key);
    }
}